import React, { Component } from 'react';
import axios from 'axios';
import PubSub from 'pubsub-js';

import User from '../User';

export default class Users extends Component {
  token = null

  state = {
    users: [],
  }

  componentDidMount() {
    // 默认先获取一次用户
    this.fetchUsers();
    this.token = PubSub.subscribe('searchKeywordChanged', (_, keyword) => {
      this.fetchUsers(keyword);
    });
  }

  componentWillUnmount() {
    PubSub.unsubscribe(this.token);
  }

  fetchUsers = async (keyword) => {
    const res = await axios.get(`/api/github/search/users?q=${keyword || 'h'}`);
    if (res && res.data) {
      this.setState({ users: res.data.items || [] });
    }
  }

  render() {
    const { users } = this.state;
    return (
      <div className="row row-cols-4 g-4">
        {users.map(user => <User key={user.node_id} user={user} />)}
      </div>
    )
  }
}
